package com.xtsoft.platform.task.controller;


import com.fasterxml.jackson.databind.JsonMappingException;
import com.xtsoft.core.controller.GenericController;
import com.xtsoft.core.repository.QueryFilter;
import com.xtsoft.core.repository.QueryResult;
import com.xtsoft.core.utils.BeanUtil;
import com.xtsoft.core.utils.ResultMsg;
import com.xtsoft.core.utils.StringUtils;
import com.xtsoft.core.utils.UUIDGenerator;

import com.xtsoft.platform.base.system.domain.SysUser;
import com.xtsoft.platform.globe.utils.SecurityUtils;
import com.xtsoft.platform.task.domain.InfTask;
import com.xtsoft.platform.task.domain.TaskComment;
import com.xtsoft.platform.task.service.InfTaskService;
import com.xtsoft.platform.task.service.TaskCommentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JsonParseException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.springframework.messaging.simp.SimpMessageHeaderAccessor.getUser;

/**
 * 
 * @ClassName:  taskComment   
 * <p> 任务点评处理类 </p>
 * @author: Codegen-代码生成器
 * @date:   2019年12月3日 上午10:59:46
 */
 @Tag(name = "任务点评--处理接口")
@RestController
public class TaskCommentController extends GenericController{
	
	private final Logger log = LoggerFactory.getLogger(TaskCommentController.class);
	
	@Autowired	
	private TaskCommentService taskCommentService;
	
	@Autowired	
	private InfTaskService infTaskService;
	
    /**
     *  <p>新增一个任务点评缺陷</p>  
     * @param taskComment 要新增的任务点评
     * @return ResponseEntity<ResultMsg>, ResultMsg的Data中包含 任务点评
     * @throws URISyntaxException 如果URI语法不正确，则抛URI语法异常                     
	 * @author Codegen-代码生成器	
	 * @date 2020-07-16 12:10:57
    */	
    @PostMapping("/taskComment/add")
	@Parameter(name = "taskComment", description = "要新增的任务点评", required = false)
	@Operation(summary = "新增，根据前台传递的任务点评新增")
    public ResponseEntity<ResultMsg> add(@RequestBody TaskComment taskComment) throws URISyntaxException {
		if(null == taskComment){
			return new ResponseEntity<ResultMsg>(new ResultMsg(false,"新增任务点评失败，传递的任务点评为空"),HttpStatus.OK); 
		}SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("新增任务点评缺陷开始......",  user.getLoginId(), user.getUsername(), getClientIp());
        if (!StringUtils.isEmpty(taskComment.getTaskCommentId())) {
		    log.info("新增任务点评缺陷失败，新任务点评不能具有taskCommentId属性值",  user.getLoginId(), user.getUsername(), getClientIp());
            return new ResponseEntity<ResultMsg>(new ResultMsg(false,"新增任务点评失败，新任务点评不能具有taskCommentId属性值"),HttpStatus.OK);
        }
        //获取任务
        InfTask infTask = infTaskService.get(taskComment.getInfTask().getInfTaskId());
        if(StringUtils.isEmpty(infTask)) {
        	taskComment.setInfTask(infTaskService.findByNodeId(taskComment.getInfTask().getInfTaskId()).get(0));
        }
        taskComment.setUpdateTime(new Date().getTime());
        taskComment.setUserId( user.getUserId());
        TaskComment result = taskCommentService.save(taskComment);
		log.info("新增任务点评成功",  user.getLoginId(), user.getUsername(), getClientIp());
        return new ResponseEntity<ResultMsg>(new ResultMsg(true,"新增成功",result),HttpStatus.OK);
    }	

    /**
     * <p>更新一个任务点评</p>    
     * @param taskComment 要更新的任务点评
     * @return ResponseEntity<ResultMsg>, json格式
     * @throws URISyntaxException 如果URI语法不正确，则抛URI语法异常
	 * @author Codegen-代码生成器
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
	 * @date 2020-07-16 12:10:57
     */
    @PostMapping("/taskComment/update")
    @Parameter(name = "taskComment", description = "要更新的任务点评", required = false)
	@Operation(summary = "更新，根据传递的 任务点评更新实体")
    public ResponseEntity<ResultMsg> update(@RequestBody TaskComment taskComment) throws URISyntaxException, IllegalAccessException, InvocationTargetException {
		if(null == taskComment){
			return new ResponseEntity<ResultMsg>(new ResultMsg(false,"更新任务点评失败，传递的任务点评为空"),HttpStatus.OK); 
		}SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("单条更新任务点评开始......",  user.getLoginId(), user.getUsername(), getClientIp());
		//若 任务点评无主键值，说明调用错误
        if (StringUtils.isBlank(taskComment.getTaskCommentId())) {
			log.info("单条更新任务点评失败，任务点评对象taskCommentId无属性值",  user.getLoginId(), user.getUsername(), getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false,"更新失败，任务点评对象taskCommentId无属性值"),HttpStatus.OK);
        }
        TaskComment taskCommentNew = taskCommentService.get(taskComment.getTaskCommentId());
        BeanUtil.copyNotNullProperties(taskCommentNew, taskComment);
        taskCommentNew.setUpdateTime(new Date().getTime());
        taskCommentNew.setUserId( user.getUserId());
        taskCommentService.save(taskCommentNew);
		log.info("单条更新任务点评成功",  user.getLoginId(), user.getUsername(), getClientIp());
        return new ResponseEntity<ResultMsg>(new ResultMsg(true,"更新成功",taskCommentNew),HttpStatus.OK);
    }  

    /**
	 *   <p>查询任务点评列表，若分页，则页码信息在Request的参数中，包括当前页，每页记录数</p>
     * @return ResponseEntity<QueryResult<taskComment>>，json格式
     * @throws URISyntaxException 如果出错，则产生页码信息的 HTTP headers
	 * @author Codegen-代码生成器
	 * @date 2020-07-16 12:10:57
     */
    @GetMapping("/taskComment/getAll")
	@Operation(summary = "查询，根据传递的条件查询任务点评列表，条件参数在Request中")
    public ResponseEntity<QueryResult<TaskComment> > getAll()
        throws URISyntaxException, JsonParseException, JsonMappingException, IOException, ParseException {
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("获取任务点评列表开始......",  user.getLoginId(), user.getUsername(), getClientIp());
        QueryFilter<TaskComment> filter=new QueryFilter<TaskComment>(TaskComment.class);
        filter.addFilterFromRequest(request);
        QueryResult<TaskComment> result= taskCommentService.anyQuery(filter);
		log.info("获取任务点评列表成功",  user.getLoginId(), user.getUsername(), getClientIp());	
        return new ResponseEntity<QueryResult<TaskComment>>(result,HttpStatus.OK);
    }
    /**
	 *   <p>根据任务点评唯一ID值获取任务点评</p>
     * @param id 任务点评唯一ID值
     * @return  ResponseEntity<taskComment>
	 * @author Codegen-代码生成器
	 * @date 2020-07-16 12:10:57		
     */
    @GetMapping("/taskComment/get/{id}")
    @Parameter(name = "id", description = "对象唯一Id", required = false)
	@Operation(summary = "获取单个任务点评，若根据任务点评唯一Id获取到了多个对象则发生异常")
    public ResponseEntity<ResultMsg> get(@PathVariable String id) {
		if(StringUtils.isBlank(id)){
			 return new ResponseEntity<ResultMsg>(new ResultMsg(false,"获取单个任务点评失败，未给定任务点评的唯一标识"),HttpStatus.OK);
		}SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("获取任务点评开始......",  user.getLoginId(), user.getUsername(), getClientIp());
        TaskComment taskComment = taskCommentService.get(id);
        if(taskComment==null) {
        	return new ResponseEntity<ResultMsg>(new ResultMsg(false,"当前任务没有点评！！无法编辑"),HttpStatus.OK);
        }
		/*
		*  <p> ofNullable执行逻辑：如果对象为空，则执行orElse，否则执行.map...
		*		return Optional.ofNullable(sysRole).map(result -> new ResponseEntity<>(result, HttpStatus.OK))
		*		.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));		
		*/
		log.info("获取任务点评成功",  user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true,"获取成功",taskComment),HttpStatus.OK);
    } 

    /**
     *     <p>根据任务点评唯一ID值删除单个任务点评</p>
     * @param  id 任务点评唯一ID值
     * @return ResponseEntity,json格式
	 * @author Codegen-代码生成器
	 * @date 2020-07-16 12:10:57		 
     */
    @GetMapping("/taskComment/delete/{id}")
    @Parameter(name = "id", description = "任务点评唯一Id", required = false)
	@Operation(summary = "删除单个任务点评")
    public ResponseEntity<ResultMsg> delete(@PathVariable String id) {
		if(StringUtils.isBlank(id)){
			 return new ResponseEntity<ResultMsg>(new ResultMsg(false,"删除单个任务点评失败，未给定任务点评的唯一标识"),HttpStatus.OK);
		}SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("删除单条任务点评开始......",  user.getLoginId(), user.getUsername(), getClientIp());
		taskCommentService.remove(id);
		log.info("删除单条任务点评成功",  user.getLoginId(), user.getUsername(), getClientIp());		
        return new ResponseEntity<ResultMsg>(new ResultMsg(true,"删除成功"),HttpStatus.OK);
    }
    /**
     * 
     * <p> 点评  </p>  
     * @param list
     * @return
     * @return ResponseEntity<ResultMsg>
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     * @throws  
     * @author litao
     * @date 2021年4月26日 
     * @time 下午3:32:12
     */
    @PostMapping("/taskComment/mark")
    @Parameter(name = "list", description = "要更新的任务点评", required = false)
	@Operation(summary = "点评")
    public ResponseEntity<ResultMsg> mark(@RequestBody List<TaskComment> list) throws IllegalAccessException, InvocationTargetException{
    	
    	
    	for (TaskComment taskComment : list) {
			SysUser user = (SysUser) SecurityUtils.getLoginedUser();
    		 TaskComment taskCommentNew = taskCommentService.get(taskComment.getTaskCommentId());
    		 BeanUtil.copyNotNullProperties(taskCommentNew, taskComment);
    	      taskCommentNew.setUpdateTime(new Date().getTime());
    	      taskCommentNew.setUserId( user.getUserId());
    	       taskCommentService.save(taskCommentNew);
		}
    	return new ResponseEntity<ResultMsg>(new ResultMsg(true),HttpStatus.OK);
    }
    /**
     * 
     * <p> 点评  </p>  
//     * @param list
     * @return
     * @return ResponseEntity<ResultMsg>
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     * @throws  
     * @author litao
     * @date 2021年4月26日 
     * @time 下午3:32:12
     */
    @PostMapping("/taskComment/mark2")
    @Parameter(name = "obj", description = "要更新的任务点评", required = false)
	@Operation(summary = "删除调度任务集合")
    public ResponseEntity<ResultMsg> mark2(@RequestBody TaskComment taskComment) throws IllegalAccessException, InvocationTargetException{
		if(null == taskComment){
			return new ResponseEntity<ResultMsg>(new ResultMsg(false,"更新任务点评失败，传递的任务点评为空"),HttpStatus.OK); 
		}SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("单条更新任务点评开始......",  user.getLoginId(), user.getUsername(), getClientIp());
		//若 任务点评无主键值，说明调用错误
        if (StringUtils.isBlank(taskComment.getTaskCommentId())) {
			log.info("单条更新任务点评失败，任务点评对象taskCommentId无属性值",  user.getLoginId(), user.getUsername(), getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false,"更新失败，任务点评对象taskCommentId无属性值"),HttpStatus.OK);
        }
        TaskComment taskCommentNew = taskCommentService.get(taskComment.getTaskCommentId());
        BeanUtil.copyNotNullProperties(taskCommentNew, taskComment);
	      taskCommentNew.setUpdateTime(new Date().getTime());
	      taskCommentNew.setUserId( user.getUserId());
	       taskCommentService.save(taskCommentNew);
		log.info("单条更新任务点评成功",  user.getLoginId(), user.getUsername(), getClientIp());
        return new ResponseEntity<ResultMsg>(new ResultMsg(true,"更新成功",taskCommentNew),HttpStatus.OK);
    }
	@PostMapping("/taskComment/upload")
	@Parameter(name = "imgFile", required = false)
	@Operation(summary = "任务点评内容")
	public Map<String, Object> upload(@RequestParam(value = "imgFile", required = false) MultipartFile content)
			throws IOException {
		String absolutePath = "";
		if (!content.isEmpty()) {
			byte[] bytes = content.getBytes();
			String uuid = UUIDGenerator.getUUID();
			String fileName = content.getOriginalFilename().replace("\"", "“");
			String path = request.getSession().getServletContext().getRealPath("/") + "/upload/" + uuid;// 绝对路径
			absolutePath = "/upload/" + uuid + "/" + fileName;// 相对路径
			Path dirpath = Paths.get(path);// 文件夹路径
			Path filepath = Paths.get(dirpath + "/" + fileName);// 文件路径
			Files.createDirectories(dirpath);// 创建文件夹
			Files.write(filepath, bytes);// 创建文件
		}
		Map<String, Object> map = new HashMap<>();
		map.put("error", 0);
		map.put("url", absolutePath);
		return map;
	}
}
